<template>
    <div id="notice-detail">
        <el-row class="card-box">
            <el-card class="form-box">
                <el-form :label-position="labePosition" label-width="125px" size="mini">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知规则名称:">
                                <el-input v-model="ruleForm.ruleName" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知类型:">
                                <el-select placeholder="请选择" style="width: 100%" v-model="ruleForm.noticeType" @change="changeNoticeType">
                                    <el-option
                                        v-for="item in noticeTypeStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="上游连接状态:" v-if="ruleForm.noticeType == '2'">
                                <el-radio v-model="ruleForm.successStatus" label="0" fill="red">连接正常</el-radio>
                                <el-radio v-model="ruleForm.successStatus" label="1">连接异常</el-radio>
                            </el-form-item>
                            <el-form-item label="引擎初始化:" v-if="ruleForm.noticeType == '3'">
                                <el-radio v-model="ruleForm.successStatus" label="0">引擎初始化成功</el-radio>
                                <el-radio v-model="ruleForm.successStatus" label="1">引擎初始化失败</el-radio>
                            </el-form-item>
                            <el-form-item label="引擎运行状态:" v-if="ruleForm.noticeType == '4'">
                                <el-radio v-model="ruleForm.successStatus" label="0">正常</el-radio>
                                <el-radio v-model="ruleForm.successStatus" label="1">异常</el-radio>
                            </el-form-item>
                            <el-form-item label="CDC运行状态:" v-if="ruleForm.noticeType == '8'">
                                <el-radio v-model="ruleForm.successStatus" label="0">监听正常</el-radio>
                                <el-radio v-model="ruleForm.successStatus" label="1">监听异常</el-radio>
                            </el-form-item>
                            <el-form-item label="CDC监听结果:" v-if="ruleForm.noticeType == '5'">
                                <el-radio v-model="ruleForm.successStatus" label="1">监听异常</el-radio>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知次数上限:">
                                <el-input v-model.trim="ruleForm.limitTimes" @input.native="onInput" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知用户:">
                                <el-tooltip effect="dark" placement="top-start" :disabled="!tooltipFunds2.length">
                                    <ul slot="content" style="min-height: 18px; max-height: 200px; overflow: auto">
                                        <li :key="item.value" v-for="item in tooltipFunds2">
                                            {{ item }}
                                        </li>
                                    </ul>
                                    <el-select
                                        placeholder="请选择"
                                        multiple
                                        clearable
                                        filterable
                                        collapse-tags
                                        v-model="ruleForm.noticeUser"
                                        style="width: 100%"
                                        @change="changeNoticeUser(ruleForm.noticeUser)"
                                    >
                                        <el-option
                                            v-for="item in userStorage"
                                            :key="item.userCode"
                                            :label="item.userName + ' ' + item.userNickName"
                                            :value="item.userCode"
                                        ></el-option>
                                    </el-select>
                                </el-tooltip>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="通知日期区间:">
                                <el-date-picker
                                    v-model="ruleForm.dates"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    style="width: 80%"
                                    @change="handleDate"
                                    value-format="yyyyMMdd"
                                    format="yyyy-MM-dd"
                                    align="center"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="通知时间段:">
                                <el-time-picker
                                    is-range
                                    v-model="ruleForm.times"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    placeholder="选择时间范围"
                                    style="width: 70%"
                                    @change="handleTime"
                                    value-format="HHmmss"
                                    format="HH:mm:ss"
                                    align="center"
                                >
                                </el-time-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="启用状态:" class="left-label">
                                <el-switch v-model="ruleForm.status" active-value="0" inactive-value="1" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="正文发送列设置:" v-show="ruleForm.noticeType == '3' || ruleForm.noticeType == '5'">
                                <el-select
                                    placeholder="请选择"
                                    multiple
                                    filterable
                                    collapse-tags
                                    style="width: 100%"
                                    clearable
                                    v-model="ruleForm.columns"
                                >
                                    <el-option
                                        v-for="item in columnsStorage"
                                        :key="item.dictKey"
                                        :label="item.dictKeyName"
                                        :value="item.dictKey"
                                    ></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <el-row>
                    <div class="link-box" v-if="isShowSubmit">
                        <el-link icon="el-icon-edit" v-show="!isEdit" @click="handleEdit">编辑</el-link>
                        <el-link icon="el-icon-view" v-show="isEdit" @click="handleEdit">预览</el-link>
                    </div>
                </el-row>
                <el-row class="email-title">
                    <h2 v-show="!isEdit">{{ ruleForm.greeting }}</h2>
                    <div v-show="isEdit" class="title-ipt">
                        <el-input v-model="ruleForm.greeting"></el-input>
                    </div>
                </el-row>
                <el-row style="margin-bottom: 10px">
                    <div v-show="!isEdit" class="text-box">{{ ruleForm.mainBody }}</div>
                    <el-input v-show="isEdit" type="textarea" autosize placeholder="请输入内容" v-model="ruleForm.mainBody"> </el-input>
                </el-row>
                <!-- <el-row v-if="ruleForm.noticeType == '2'">
                    <div style="width: 100%; height: calc(100vh - 600px)" class="emailContent2">
                        <tr>
                            <td>检测时间：</td>
                            <td>2022-09-12 12:00:09</td>
                            <td>上游系统：</td>
                            <td>估值（估值数据）</td>
                            <td>连接状态：</td>
                            <td>连接异常</td>
                        </tr>
                    </div>
                </el-row> -->
                <el-row v-if="ruleForm.noticeType == '3' || ruleForm.noticeType == '5'">
                    <el-table ref="emailTable" :data="emailTable" border size="mini" style="width: 100%" height="calc(100vh - 600px)">
                        <el-table-column v-for="i in emailTableColumns" :prop="i.dictKey" :key="i.dictKey" :label="i.dictKeyName" min-width="100">
                        </el-table-column>
                    </el-table>
                </el-row>
                <!-- <el-row v-if="ruleForm.noticeType == '4'">
                    <div style="width: 100%; height: calc(100vh - 600px)" class="emailContent2">
                        <tr>
                            <td>检测时间：</td>
                            <td>2022-09-12 12:00:09</td>
                            <td>引擎运行状态：</td>
                            <td>异常</td>
                        </tr>
                    </div>
                </el-row> -->
            </el-card>
        </el-row>
        <el-row class="card-box">
            <el-card>
                <div class="btns">
                    <el-button @click="$emit('close-tab', data.name)">取消</el-button>
                    <el-button v-if="isShowSubmit" type="primary" @click="submit" :loading="btnLoading">确认</el-button>
                </div>
            </el-card>
        </el-row>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import RiskEntryInputs from '@/common/components/risk-entry-inputs.vue';

@Component({
    name: 'WarningNoticeDetail',
    components: { RiskEntryInputs },
})
export default class WarningNoticeDetail extends Vue {
    @Prop() data: any;

    private labePosition: string = 'right';

    private ruleForm: any = {
        ruleName: '',
        noticePanel: '',
        noticeType: '3',
        thresholdType: '',
        limitTimes: '',
        dates: [],
        startDate: '',
        endDate: '',
        fundCode: '',
        fundGroup: [],
        times: null,
        startTime: 0,
        endTime: 0,
        noticeUser: [],
        columns: [],
        status: '0',
        greeting: '服务执行监控-引擎状态监控通知',
        mainBody: '尊敬的领导：\n您好！\n根据智能风控工作台监控，"引擎状态监控"有更新变动，请及时关注！',
        successStatus: '1',
    };

    private noticePanelStorage: any[] = [];

    private thresholdTypeStorage: any[] = [];

    private noticeTypeStorage: any[] = [
        // { dictKey: '1', dictKeyName: '条目监控' },
        // { dictKey: '2', dictKeyName: '上游连接状态' },
        { dictKey: '3', dictKeyName: '引擎初始化' },
        { dictKey: '4', dictKeyName: '引擎运行状态' },
        // { dictKey: '5', dictKeyName: 'CDC监听结果' },
        // { dictKey: '8', dictKeyName: 'CDC运行状态' },
    ];

    private fundGroup: any[] = [];

    private userStorage: any[] = [];

    private showType: string = 'add';

    private btnLoading: boolean = false;

    private columnsStorage: any[] = [];
    private columnsObj = {};

    private emailTable: any[] = [
        {
            entryCode: '',
            entryName: '',
            thresholdValue: '',
            fundName: '',
            calculateValue: '',
            calculateLogic: '',
            stockCode: '',
            stockName: '',
            remark: '',
            handleUser: '',
        },
    ];
    private tooltipFunds2: any[] = []; // 通知用户tooltip

    private isEdit: boolean = false; // 文本是否在编辑状态
    async mounted() {
        // 通知面板下拉框
        this.getNoticePanelList();
        // 用户列表
        this.getUserList();
        // 账户组
        this.getFundGroupList();
        // 触警类型下拉框
        this.thresholdTypeStorage = await SGU_CACHE('ThresholdType', '/dict/list/code/Y_000039', []);
        // 邮件通知类型
        // this.noticeTypeStorage = await SGU_CACHE('NoticeType', '/dict/list/code/Y_000266', []);
        // 邮件表格列下拉框
        // this.columnsStorage = await SGU_CACHE('Columns', '/dict/list/code/Y_000273', []);
        // console.log('99999', this.columnsStorage, DictionConstUtil.ListToPojo(this.columnsStorage));
        // this.columnsObj = DictionConstUtil.ListToPojo(this.columnsStorage);
        console.log('data', this.data);

        if (this.data.type.indexOf('add') > -1) {
            this.ruleForm.columns = this.columnsStorage.map(i => i.dictKey);
        }
    }

    // 监听父组件带进来的基础数据
    @Watch('data', { immediate: true, deep: true })
    watchData(newData) {
        if (newData) {
            console.log('newData', newData);
            if (newData.content) {
                let data = JSON.parse(JSON.stringify(newData.content));
                data.dates = [String(...(data.startDate || '')), String(...(data.endDate || ''))];
                let timefor = '';
                let timeafter = '';
                if (data.startTime != undefined && data.startTime !== '') {
                    timefor = String(data.startTime);
                    // 补全时间格式
                    if (String(data.startTime).length < 6) {
                        for (let i = 0; i < 6 - String(data.startTime).length; i++) {
                            timefor = '0' + timefor;
                        }
                    }
                }
                if (data.endTime != undefined && data.endTime !== '') {
                    timeafter = String(data.endTime);
                    if (String(data.endTime).length < 6) {
                        for (let j = 0; j < 6 - String(data.endTime).length; j++) {
                            timeafter = '0' + timeafter;
                        }
                    }
                }
                if (timefor && timeafter) {
                    data.times = [timefor, timeafter];
                } else {
                    data.times = null;
                }
                this.ruleForm = data ?? this.ruleForm;
            }
            this.showType = newData.type;
        }
    }
    @Watch('ruleForm.noticeType', { immediate: true, deep: true })
    watchNoticeType(newData) {
        console.log('newData', newData, this.ruleForm.columns);
        this.columnsStorage = [];
        // this.ruleForm.columns = [];
        if (newData == '3') {
            this.columnsStorage = [
                { dictKey: 'tableName', dictKeyName: '表名' },
                { dictKey: 'loadSize', dictKeyName: '数据加载量(GB)' },
                { dictKey: 'loadAmount', dictKeyName: '数据加载条数' },
                { dictKey: 'finishTimes', dictKeyName: '加载时长(ms)' },
                { dictKey: 'resultType', dictKeyName: '结果' },
                { dictKey: 'logInfo', dictKeyName: '日志信息' },
                { dictKey: 'loadDate', dictKeyName: '加载时间' },
            ];
        } else if (newData == '5') {
            this.columnsStorage = [
                { dictKey: 'dataSource', dictKeyName: '数据源' },
                { dictKey: 'tableName', dictKeyName: '表名' },
                { dictKey: 'kafkaValue', dictKeyName: '消息内容' },
                { dictKey: 'monitorResultType', dictKeyName: '监听结果' },
                { dictKey: 'logInfo', dictKeyName: '日志信息' },
                { dictKey: 'finishedTimes', dictKeyName: '监听耗时' },
                { dictKey: 'receiveTimestamp', dictKeyName: '监听时间' },
            ];
        }
    }

    get emailTableColumns() {
        let columns = [];
        for (let i = 0; i < this.ruleForm.columns?.length; i++) {
            const element = this.ruleForm.columns[i];

            if (this.columnsStorage.length) {
                // columns.push(this.columnsStorage.find(item => item.dictKey === element));
                for (let j = 0; j < this.columnsStorage.length; j++) {
                    if (this.columnsStorage[j].dictKey === element) {
                        columns.push(this.columnsStorage[j]);
                    }
                }
            }
        }

        return columns;
    }

    get isShowSubmit() {
        return ['addEngine', 'editEngine'].includes(this.showType);
    }

    private getNoticePanelList() {
        this.$axios.get('/entry/subscribe/all/panel/user').then((res: any) => {
            this.noticePanelStorage = res;
        });
    }

    private getUserList(): void {
        this.$axios.get('/userManage/user/list').then((res: any) => {
            if (res) {
                // console.log('通知用户', res);
                this.userStorage = res;
            }
        });
    }

    // 获取账户组数据
    private getFundGroupList(): void {
        this.$axios.post('/fundGroup/list').then((res: any) => {
            this.fundGroup = res;
        });
    }

    private handleDate(val: any) {
        if (val && val.length) {
            this.ruleForm.startDate = val[0];
            this.ruleForm.endDate = val[1];
            // this.ruleForm.dates = [val[0], val[1]];
            return;
        }
        this.ruleForm.dates = [];
        this.ruleForm.startDate = 0;
        this.ruleForm.endDate = 0;
    }

    private handleTime(val: any) {
        if (val && val.length) {
            this.ruleForm.startTime = val[0];
            this.ruleForm.endTime = val[1];
            return;
        }
        this.ruleForm.startTime = 0;
        this.ruleForm.endTime = 0;
    }

    private getAccountControlValue(val: any) {
        this.ruleForm.fundCode = val;
    }

    private submit() {
        if (!this.verify()) {
            return;
        }
        this.btnLoading = true;

        let urlType = {
            addEngine: '/notice/monitor/rule/add',
            editEngine: '/notice/monitor/rule/update',
        };
        if (this.ruleForm.startTime == 0 && this.ruleForm.endTime == 0) {
            this.ruleForm.startTime = null;
            this.ruleForm.endTime = null;
        }

        if (this.ruleForm.startDate == 0 && this.ruleForm.endDate == 0) {
            this.ruleForm.startDate = null;
            this.ruleForm.endDate = null;
        }
        let url = urlType[this.showType];
        this.$axios({ url, method: 'post', data: this.ruleForm })
            .then((res: any) => {
                this.btnLoading = false;
                this.$message({ type: 'success', message: '操作成功！' });
                this.$emit('close-tab', this.data.name);
            })
            .catch(() => {
                this.btnLoading = false;
            });
    }

    private verify() {
        if (!this.ruleForm.ruleName) {
            this.$message({ type: 'warning', message: '通知规则名称不能为空！' });
            return false;
        }
        console.log('this.ruleForm.noticeUser', this.ruleForm.noticeUser, this.ruleForm.columns);
        if (!this.ruleForm.noticeUser.length) {
            this.$message({ type: 'warning', message: '通知用户不能为空！' });
            return false;
        }
        console.log(this.ruleForm.limitTimes, 'this.ruleForm.limitTimes');

        let reg = /^[1-9]\d*$/g;
        if (!reg.test(this.ruleForm.limitTimes)) {
            // this.$message({ type: 'warning', message: '通知次数上限不能小于1！' });
            // return false; 为空默认为不设置上限
        }
        if (this.ruleForm.limitTimes == '0') {
            this.$message({ type: 'warning', message: '通知次数上限不能小于1！' });
            return false;
        }
        if (this.ruleForm.noticeType == '3') {
            if (!this.ruleForm.columns.length) {
                this.$message({ type: 'warning', message: '正文发送列不能为空！' });
                return false;
            }
        }

        return true;
    }

    private handleEdit() {
        this.isEdit = !this.isEdit;
    }

    private onInput(e) {
        e.target.value = e.target.value.replace(/[^0-9]/g, '');
    }
    // 通知类型选择
    changeNoticeType(val) {
        if (val == '2') {
            this.ruleForm.greeting = '服务执行监控-上游连接状态通知';
            this.ruleForm.mainBody = '尊敬的领导：\n您好！\n根据智能风控工作台监控，"上游连接状态"有更新变动，请及时关注！';
        } else if (val == '3') {
            this.ruleForm.greeting = '服务执行监控-引擎状态监控通知';
            this.ruleForm.mainBody = '尊敬的领导：\n您好！\n根据智能风控工作台监控，"引擎状态监控"有更新变动，请及时关注！';
            // this.ruleForm.columns = [];
        } else if (val == '4') {
            this.ruleForm.greeting = '服务执行监控-引擎状态监控通知';
            this.ruleForm.mainBody = '尊敬的领导：\n您好！\n根据智能风控工作台监控，"引擎状态监控-引擎运行状态"有更新变动，请及时关注！';
        } else if (val == '5') {
            // this.ruleForm.columns = [];
            this.ruleForm.greeting = 'CDC监听结果';
            this.ruleForm.mainBody = '尊敬的领导：\n您好！\n根据智能风控工作台监控，"CDC监听结果"有更新变动，请及时关注！';
        } else if (val == '8') {
            // this.ruleForm.columns = [];
            this.ruleForm.greeting = 'CDC运行状态';
            this.ruleForm.mainBody = '尊敬的领导：\n您好！\n根据智能风控工作台监控，"CDC运行状态"有更新变动，请及时关注！';
        }
        this.ruleForm.columns = [];
    }
    changeNoticeUser(val) {
        let arr = [];
        val.forEach(item => {
            let obj = this.userStorage.find(element => item === element['userCode']);
            if (obj) {
                arr.push(obj.userName + ' ' + obj.userNickName + ',');
            }
        });

        this.$nextTick(() => {
            this.tooltipFunds2 = arr;
        });
    }
}
</script>
<style lang="scss" scoped>
#notice-detail {
    .card-box {
        margin-bottom: 10px;
        .form-box {
            .left-label {
                /deep/ .el-form-item__label {
                    width: 125px !important;
                }
                /deep/ .el-form-item__content {
                    margin-left: 80px !important;
                }
            }
            /deep/ .el-input--mini {
                width: 70%;
            }
            /deep/ .el-form-item__label {
                color: black;
            }
            // /deep/ .el-date-editor .el-range-separator {
            //     padding: 0 15px;
            // }
        }
        .email-title {
            margin-bottom: 20px;
            h2 {
                text-align: center;
                font-size: 1.5em;
            }
            .title-ipt {
                width: 400px;
                margin: 0 auto;
                /deep/ .el-input__inner {
                    font-size: 1.5em;
                }
            }
        }
        .emailContent2 {
            padding-left: 5px;
            tr td:nth-child(odd) {
                font-size: 20px;
            }
            tr td:nth-child(even) {
                font-size: 20px;
                font-weight: bold;
                color: #ad1525;
            }
            tr td:nth-child(3),
            tr td:nth-child(5) {
                padding-left: 20px;
            }
        }

        .text-box {
            font-family: monospace;
            font-size: inherit;
            white-space: pre-wrap;
        }
        .link-box {
            float: right;
            padding-right: 10px;
            /deep/ .el-link {
                margin: 0 5px;
            }
        }
        .btns {
            display: inline;
            float: right;
            padding-bottom: 20px;
        }
    }
}
/deep/ .el-radio__inner {
    border-radius: 2px;
}

/deep/ .el-radio__input.is-checked .el-radio__inner::after {
    content: '';
    width: 10px;
    height: 5px;
    border: 1px solid white;
    border-top: transparent;
    border-right: transparent;
    text-align: center;
    display: block;
    position: absolute;
    top: 2px;
    left: 0px;
    vertical-align: middle;
    transform: rotate(-45deg);
    border-radius: 0px;
    background: none;
}

/deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 95px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/deep/ .el-tag__close.el-icon-close {
    top: -5px;
}
/deep/ .el-radio:first-of-type .el-radio__label {
    color: #768b21 !important;
}
/deep/ .el-radio:last-of-type .el-radio__label {
    color: #a5152e !important;
}
// /deep/ .el-radio__input.is-checked .el-radio__inner {
//     background: white !important;
//     &:hover {
//         border-color: #28d4c1;
//     }
// }

/deep/ .el-date-editor .el-range-separator {
    width: auto;
}
</style>
